<?php

namespace App\Http\Controllers;

use App\Http\Resources\TopicResource;
use App\Models\Topic;
use App\Http\Requests\StoreTopicRequest;
use App\Http\Requests\UpdateTopicRequest;
use Illuminate\Support\Facades\Auth;

class TopicController extends Controller {
    public function __construct() {
        $this->middleware(['auth:sanctum'])->except(['index','show','per_cat']);
    }

    /**
     * Display a listing of the resource.
     */
    public function index() {
        $topics = Topic::when(request('keywords'),function($query,$keywords){
            $query->where(request('key'),'like',"%{$keywords}%");
        })->orderBy('sort')->with(['user','cat'])->latest()->paginate(12);
        return TopicResource::collection($topics);
    }
    public function per_cat($c_id) {
        $topics = Topic::where('cat_id',$c_id)->orderBy('sort')->with(['user','cat'])->latest()->paginate(8);
        return TopicResource::collection($topics);
    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreTopicRequest $request,Topic $topic) {
        $topic->fill($request->input());
        $topic->user_id = Auth::id();
        $topic->save();
        return $this->success('发布帖子成功',new TopicResource($topic->load(['user','cat'])));
    }

    /**
     * Display the specified resource.
     */
    public function show(Topic $topic)
    {
        $topic->html = $topic->html;
        return $this->success(data:new TopicResource($topic->load(['user','cat'])));
    }



    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateTopicRequest $request, Topic $topic) {
        $this->authorize('update',$topic);
        $topic->fill($request->input())->save();
        return $this->success('帖子修改成功',new TopicResource($topic->load(['user','cat'])));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Topic $topic) {
        $this->authorize('delete',$topic);
        $topic->delete();
        return $this->success('帖子删除成功');
    }

    public function get_one_user_topics(){
        //http://bbs.test?u_id=2&page=1;
       $topics = Topic::with('user')->when(request('u_id'),function($query){
           return $query->where('user_id',request('u_id'));
       })->latest()->paginate(5);
       return TopicResource::collection($topics);
    }
}
